<template>
  <div>
    <h2 style="text-align: center">发布新课程</h2>

    <!-- 步骤条 -->
    <el-steps
      :active="active"
      finish-status="success"
      align-center
      style="margin-top: 20px"
    >
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="最终发布"></el-step>
    </el-steps>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-col :span="10">
          <el-input
            v-model="courseInfo.title"
            placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"
          />
        </el-col>
      </el-form-item>

      <!-- 所属分类 TODO -->
      <el-form-item label="课程分类">
        <el-select
          @change="getsubjectsTwo"
          placeholder="请选择"
          v-model="courseInfo.subjectParentId"
        >
          <el-option
            v-for="subject in subjects"
            :label="subject.title"
            :value="subject.id"
            :key="subject.id"
          />
        </el-select>

        <el-select placeholder="二级分类" v-model="courseInfo.subjectId">
          <el-option
            v-for="subject in subjectsTwo"
            :label="subject.title"
            :value="subject.id"
            :key="subject.id"
          />
        </el-select>
      </el-form-item>

      <!-- 课程讲师 TODO -->
      <el-form-item label="首选讲师">
        <el-select v-model="courseInfo.teacherId">
          <el-option
            ch
            v-for="teacher in teachers"
            :label="teacher.name"
            :value="teacher.id"
            :key="teacher.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfo.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时数"
        />
      </el-form-item>

      <!-- 课程简介 TODO -->
      <el-form-item label="课程简介">
        <el-col :span="15">
          <tinymce v-model="courseInfo.description" :height="300" />
        </el-col>
      </el-form-item>

      <!-- 课程封面 TODO -->
      <el-form-item label="课程封面">
        <el-upload
          class="avater-upload"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :action="BASE_API + '/eduoss/fileoss/upload'"
          :show-file-list="false"
        >
          <img :src="courseInfo.cover" style="width: 200px; height: 200px" />
        </el-upload>
      </el-form-item>

      <!-- 课程价格 -->
      <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        />
        元
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存并下一步</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import courseApi from "@/api/edu/course";
import Tinymce from "@/components/Tinymce";
export default {
  name: "Info",
  components: { Tinymce },
  data() {
    return {
      BASE_API: process.env.BASE_API,
      active: 1,
      saveBtnDisabled: false,
      courseInfo: {
        title: "",
        subjectId: "", //二级分类
        subjectParentId: "", //一级分类
        teacherId: "",
        lessonNum: "",
        description: "",
        cover:
          "https://guli-dq-1310347558.cos.ap-chengdu.myqcloud.com/guli/91c5c9fd474d4d10a9dd86242057daf0.jpg",
        price: 0,
      },
      subjects: [], //用于获取所有分类 一级 二级
      subjectsTwo: [], //用于获取当前分类的二级分类
      teachers: [], //用于获取所有老师id  name
      courseId: "", //用于数据回显的课程id
    };
  },
  created() {
    //获取courseId
    this.init();
  },
  watch: {
    $route(to, from) {
      this.init();
    },
  },
  methods: {
    //初始化页面
    init() {
      //获取courseId
      this.getTeacherList();
      if (this.$route.params && this.$route.params.id) {
        this.courseId = this.$route.params.id;
        this.getCourseInfo();
      } else {
        //初始化所有老师
        //初始化所有的一级分类
        this.getSubjectList();
        //刷新页面清空表单数据 除了url
        this.courseId = "";
        this.courseInfo = {};
        this.courseInfo.cover =
          "https://guli-dq-1310347558.cos.ap-chengdu.myqcloud.com/guli/34a13c301b1946648b25d8e979c1fdbd.jpg";
      }
    },

    //根据courseId回显数据
    getCourseInfo() {
      courseApi.getCourseInfo(this.courseId).then((response) => {
        this.courseInfo = response.data;
        //获取所有分类
        courseApi.getSubjectList().then((response) => {
          this.subjects = response.data;
          for (let i = 0; i < this.subjects.length; i++) {
            var element = this.subjects[i];
            if (element.id === this.courseInfo.subjectParentId) {
              this.subjectsTwo = element.children;
              console.log(this.subjectsTwo);
            }
          }
        });
      });
    },

    // 上次头像成功
    /**
     * 1. 上传之前  约定大小  类型
     * 2. 上传成功
     */
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是JPG格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过2MB!");
      }
      return isJPG && isLt2M;
    },
    uploadSuccess(res, file) {
      console.log(res);
      this.courseInfo.cover = res.data.picUrl;
    },

    //点击一级分类触发二级分类
    getsubjectsTwo(value) {
      this.subjects.forEach((element) => {
        if (element.id === value) {
          this.subjectsTwo = element.children;
          //自动切换绑定  或者直接清空subjectId
          if (this.subjectsTwo.length > 0 || this.subjectsTwo != null) {
            this.courseInfo.subjectId = this.subjectsTwo[0].id;
          } else {
            this.courseInfo.subjectId = "";
          }
        }
      });
    },

    //查询所有课程分类
    getSubjectList() {
      courseApi.getSubjectList().then((response) => {
        this.subjects = response.data;
      });
    },

    // 查询所有的老师
    getTeacherList() {
      courseApi.getTeacherList().then((response) => {
        this.teachers = response.data;
        // console.log(this.teachers);
      });
    },

    // 添加 课程与简介
    saveOrUpdate() {
      /**
       * 判断courseInfo
       * 没有id值 添加
       * 有id值   修改
       */
      if (!this.courseInfo.id) {
        //添加
        this.addCourse();
      } else {
        //修改
        this.updateCourse();
      }
    },

    //添加操作  会返回courseId
    addCourse() {
      courseApi.addCourse(this.courseInfo).then((response) => {
        this.$message({
          type: "success",
          message: "添加课程信息成功",
        });

        this.$router.push({
          path: `/course/chapter/${response.data.courseId}`,
        });
      });
    },

    //修改操作  不会返回courseId但是url中有并且获取了
    updateCourse() {
      courseApi.updateCourseInfo(this.courseInfo).then((response) => {
        this.$message({
          type: "success",
          message: "修改课程信息成功",
        });

        this.$router.push({
          path: `/course/chapter/${this.courseId}`,
        });
      });
    },
  },
};
</script>

<style scpoe>
</style>